package com.rc.saas.mini.service.invoice;

import com.alibaba.fastjson.JSON;
import com.github.dozermapper.core.Mapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.mini.common.base.TResponse;
import com.rc.saas.mini.common.constant.WebConstant;
import com.rc.saas.mini.common.mq.MqConfig;
import com.rc.saas.mini.common.mq.MqProducer;
import com.rc.saas.mini.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.mini.common.sms.AliyunSmsUtil;
import com.rc.saas.mini.mapper.invoice.InvoiceApplyMapper;
import com.rc.saas.mini.mapper.invoice.InvoiceMapper;
import com.rc.saas.mini.mapper.invoice.InvoiceOrderMapper;
import com.rc.saas.mini.mapper.order.OrderInfoMapper;
import com.rc.saas.mini.mapper.tenant.TenantInvoiceInfoMapper;
import com.rc.saas.mini.model.elec.ElecStation;
import com.rc.saas.mini.model.elec.ElecStationExample;
import com.rc.saas.mini.model.enterprise.EnterpriseMember;
import com.rc.saas.mini.model.invoice.*;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.model.order.OrderInfoExample;
import com.rc.saas.mini.model.rc.RcMsgNotification;
import com.rc.saas.mini.model.tenant.Tenant;
import com.rc.saas.mini.model.tenant.TenantInvoiceInfo;
import com.rc.saas.mini.model.tenant.TenantInvoiceInfoExample;
import com.rc.saas.mini.service.elec.ElecStationService;
import com.rc.saas.mini.service.enterprise.EnterpriseMemberService;
import com.rc.saas.mini.service.invoice.pojo2.ElectroniceStock;
import com.rc.saas.mini.service.invoice.pojo2.ReturnElectronice;
import com.rc.saas.mini.service.invoice.service.IEliWebService2;
import com.rc.saas.mini.service.invoice.service.InvoiceWebService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.rc.RcMsgNotificationService;
import com.rc.saas.mini.service.sms.TenantSmsService;
import com.rc.saas.mini.service.tenant.TenantOpenServiceService;
import com.rc.saas.mini.service.tenant.TenantService;
import com.rc.saas.mini.vo.invoice.ElecInvoiceVo;
import com.rc.saas.mini.vo.invoice.InvoiceApplyVo;
import com.rc.saas.mini.vo.invoice.InvoiceApplyWithIdVo;
import com.rc.saas.mini.vo.order.OrderInfoVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangzhengwei
 * @create 2021/4/28
 */
@Service
public class InvoiceApplyServiceImpl implements InvoiceApplyService {
    private static Logger logger = LogManager.getLogger(InvoiceApplyServiceImpl.class);

    @Autowired
    private InvoiceMapper invoiceMapper;


    @Autowired
    private InvoiceOrderMapper invoiceOrderMapper;

    @Override
    public InvoiceApplyMapper getMapper() {
        return invoiceApplyMapper;
    }

    @Autowired
    private InvoiceApplyMapper invoiceApplyMapper;

    @Autowired
    private TenantInvoiceInfoMapper tenantInvoiceInfoMapper;

    @Autowired
    private InvoiceOrderService invoiceOrderService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private TenantOpenServiceService tenantOpenServiceService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private InvoiceWebService invoiceWebService;

    @Autowired
    private TenantSmsService tenantSmsService;

    @Autowired
    private Mapper dozerMapper;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private MqProducer mqProducer;
    @Autowired
    private RcMsgNotificationService rcMsgNotificationService;

    @Override
    public PageInfo<InvoiceApplyVo> listPageInvoiceApply(Long memberId, String invoiceNormalType, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<InvoiceApplyVo> invoiceApplies = invoiceApplyMapper.listInvoiceApply(memberId, invoiceNormalType);

        //个人开票
        if ("0".equals(invoiceNormalType)) {
            //当发票申请通过时，发票的地址返回給前端
            List<Long> applyList = invoiceApplies.stream().map(InvoiceApplyVo::getInvoiceApplyId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(applyList)) {
                InvoiceExample example = new InvoiceExample();
                example.createCriteria().andInvoiceApplyIdIn(applyList);
                List<Invoice> invoiceList = invoiceService.selectByExample(example);

                if (!CollectionUtils.isEmpty(invoiceList)) {
                    for (InvoiceApplyVo invoiceApply : invoiceApplies) {
                        Invoice invoice1 = invoiceList.stream().filter(invoice -> invoiceApply.getInvoiceApplyId().equals(invoice.getInvoiceApplyId())).findFirst().orElseGet(() -> null);
                        invoiceApply.setInvoiceURL(invoice1 != null && invoice1.getPdfUrl() != null ? invoice1.getPdfUrl() : null);
                    }
                }
            }
        }
        return new PageInfo<>(invoiceApplies);
    }

    @Override
    public InvoiceApplyVo selectInvoiceApplyById(Long invoiceApplyId) {
        InvoiceApplyVo invoiceApplyVo = invoiceApplyMapper.selectInvoiceApplyById(invoiceApplyId);
        Invoice invoice = invoiceService.selectInvoiceByApplyId(invoiceApplyId);
        invoiceApplyVo.setInvoiceURL(invoice != null && invoice.getPdfUrl() != null ? invoice.getPdfUrl() : null);
        return invoiceApplyVo;
    }

    @Override
    public InvoiceApplyVo selectInvoiceApplyByOrderId(Long orderId) {
        return invoiceApplyMapper.selectInvoiceApplyByOrderId(orderId);

    }

    @Override
    public List<InvoiceApplyWithIdVo> listByOrderIds(List<Long> ids) {
        //查找用户最新审核的数据

        return invoiceApplyMapper.listByOrderIds(ids);
    }

    @Override
    public TResponse createInvoice(InvoiceApplyVo addInvoiceVo, MemberInfo member) {
        List<Long> orderIdList = Arrays.stream(addInvoiceVo.getOrderIdStr().split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        //订单排除
        //审核中和审核通过的订单
        InvoiceApplyExample invoiceApplyExample = new InvoiceApplyExample();
        invoiceApplyExample.createCriteria().andMemberIdEqualTo(member.getMemberId()).andStatusNotEqualTo(WebConstant.CON2);
        List<InvoiceApply> invoiceApplies = invoiceApplyMapper.selectByExample(invoiceApplyExample);
        //审核中和审核通过的订单 和订单id
        List<Long> invoiceApplyIds = invoiceApplies.stream().map(InvoiceApply::getInvoiceApplyId).collect(Collectors.toList());
        List<InvoiceOrder> invoiceOrderList = new ArrayList<>();
        if (invoiceApplyIds.size() > 0) {
            InvoiceOrderExample example = new InvoiceOrderExample();
            example.createCriteria().andInvoiceApplyIdIn(invoiceApplyIds).andMemberIdEqualTo(member.getMemberId()).andOrderIdIn(orderIdList);
            invoiceOrderList = invoiceOrderService.selectByExample(example);
        }


        //查询充电结束订单

        //OrderInfoExample orderInfoExample = new OrderInfoExample();
        //orderInfoExample.createCriteria().andOrderIdIn(orderIdList).andMemberIdEqualTo(member.getMemberId()).andStatusEqualTo(WebConstant.CON2);
        //List<OrderInfo> orderInfoList = orderInfoService.selectByExample(orderInfoExample);
        List<OrderInfo> orderInfoList = orderInfoService.listByInvoice(orderIdList,member.getMemberId());

        if (invoiceOrderList.size() > 0) {
            List<String> orderNums = new ArrayList<>();
            invoiceOrderList.forEach(invoiceOrder -> {
                List<OrderInfo> list = orderInfoList.stream().filter(order -> order.getOrderId().equals(invoiceOrder.getOrderId())).collect(Collectors.toList());
                orderNums.add(list.get(0).getOrderNum());
            });
            logger.info("invoice.checkOrderInvoice:" + orderNums.toString() + ",该订单号已经在申请中，请重新选择！");
            return TResponse.FAIL(orderNums.toString() + ",该订单号已经在申请中，请重新选择！");
        }

        //订单 区分，代开发票和自开发票

        List<Long> elecstationId = new ArrayList<>(orderInfoList.stream().map(OrderInfo::getElecStationId).collect(Collectors.toSet()));
        ElecStationExample elecStationExample = new ElecStationExample();
        elecStationExample.createCriteria().andElecStationIdIn(elecstationId);
        List<ElecStation> elecStations = elecStationService.selectByExample(elecStationExample);
        //代开发票和自开发票
        HashMap<Long, List<Long>> proxyhashMap = new HashMap<>(20);
        List<Long> selfOrderIds = new ArrayList<>();
        List<Long> selfOrderNotIds = new ArrayList<>();

        //电子发票  判断是否开通电子发票
        Boolean isEinvoice = tenantOpenServiceService.isServiceTypeCode(member.getTenantCode(), "EINVOICE");

        for (OrderInfo orderInfo : orderInfoList) {
            ElecStation elecStationCurrent = elecStations.stream().filter(elecStation -> orderInfo.getElecStationId().equals(elecStation.getElecStationId())).findFirst().orElseGet(() -> null);
            if ("1".equals(elecStationCurrent.getProxyType())) {
                //代开
                if (proxyhashMap.get(elecStationCurrent.getElecStationId()) != null) {
                    proxyhashMap.get(elecStationCurrent.getElecStationId()).add(orderInfo.getOrderId());
                } else {
                    proxyhashMap.put(elecStationCurrent.getElecStationId(), new ArrayList<Long>() {{
                        add(orderInfo.getOrderId());
                    }});
                }
            } else {
                if (member.getTenantCode().equals(orderInfo.getTenantCode()) && isEinvoice) {
                    //自开
                    selfOrderIds.add(orderInfo.getOrderId());
                } else {
                    selfOrderNotIds.add(orderInfo.getOrderId());
                }

            }
        }
        //电子发票
        if (selfOrderIds.size() > 0) {

            if (!isEinvoice) {
                return TResponse.FAIL("电子发票功能尚未开通！");
            }
            TenantInvoiceInfoExample tenantInvoiceInfoExample = new TenantInvoiceInfoExample();
            tenantInvoiceInfoExample.createCriteria().andTenantCodeEqualTo(member.getTenantCode());
            List<TenantInvoiceInfo> tenantInvoiceInfos = tenantInvoiceInfoMapper.selectByExample(tenantInvoiceInfoExample);
            if (tenantInvoiceInfos == null || tenantInvoiceInfos.size() == 0) {
                return TResponse.FAIL("运营商电子发票信息不存在！");
            }
            Tenant tenant = tenantService.selectByTenantCode(member.getTenantCode());
            //统计总金额
            ElecInvoiceVo elecInvoiceVo = orderInfoService.countInvoiceByOrder(selfOrderIds, member.getTenantCode());

            logger.info("电子开票数据;优惠金额:" + elecInvoiceVo.getDiscountAmount() + "电费金额:" + elecInvoiceVo.getChargeAmount() + "服务费金额:" + elecInvoiceVo.getServiceAmount());
            if (elecInvoiceVo.getDiscountAmount() != null && elecInvoiceVo.getDiscountAmount().compareTo(BigDecimal.ZERO) > 0) {
                elecInvoiceVo.setDiscountAmount(elecInvoiceVo.getDiscountAmount().negate());
            }

            //10正票正常开具 11正票错票重开 20 退货折让红票、21 错票重开红
            addInvoiceVo.setCZDM("10");
            // 1正票、2红票
            addInvoiceVo.setKPLX("1");
            //正式开票环境 正式上线时需要更换
            ReturnElectronice invEli = invoiceWebService.createInvEli(addInvoiceVo, elecInvoiceVo, tenantInvoiceInfos.get(0), member);
            //测试开票环境
            //ReturnElectronice invEli = invoiceWebTestService.createInvEli(addInvoiceVo, elecInvoiceVo, tenantInvoiceInfos.get(0));
            logger.info("电子开票请求,会员ID:{},开票金额:{},是否成功:{},返回信息:{}", member.getMemberId(), elecInvoiceVo.getChargeAmount().add(elecInvoiceVo.getServiceAmount()).add(elecInvoiceVo.getDiscountAmount())
                    , invEli.getReturnCode().getValue(), invEli.getReturnMsg().getValue());
            // invEli.getReturnCode().getValue(), invEli.getReturnMsg().getValue());
            if (!"0000".equals(invEli.getReturnCode().getValue())) {
                //开票失败就返回 后面的不操作
                TResponse tResponseFail = TResponse.FAIL();
                tResponseFail.put(invEli);
                return tResponseFail;
            }
            //查询发票库存
            IEliWebService2 wb = new IEliWebService2();
            /*参数类型*/
            ElectroniceStock electroniceStock = wb.getIEliWebServiceHttpPort().queryEliStock(tenantInvoiceInfos.get(0).getSellerCode());
            if (50 > Integer.valueOf(electroniceStock.getSYFPFS().getValue())) {
                List<String> mobiles = Arrays.stream(tenantInvoiceInfos.get(0).getRemindMobiles().split(",")).map(s -> s.trim()).collect(Collectors.toList());
                for (String mobile : mobiles) {
                    AliyunSmsUtil.sendSms(mobile, electroniceStock.getSYFPFS().getValue(), AliyunSmsTemplateEnum.SMS_169101549, tenant.getSmsSign());
                    tenantSmsService.updateTenantSmsByTenantCode(member.getTenantCode(), null, null, null, mobile, "0", AliyunSmsTemplateEnum.SMS_169101549.getMsgData(),
                            electroniceStock.getSYFPFS().getValue(), null);
                }
            }
            //申请以及，invoiceApplyStatus 0未审核，1审核通过，2审核不通过 ,String invoiceApplyProxyType 代开标记 0否 1是 默认0 String invoiceOrderUpdateflag (0 已开票 1未开票 ,默认0)
            // InvoiceNormalType  开票类型 0个人开票 1企业开票 默认0',
            this.insertRetrunId(member, addInvoiceVo, selfOrderIds, orderInfoList, "1", "0", "0", invEli, "0");
        }


        if ("2".equals(addInvoiceVo.getInvoiceType())) {
            addInvoiceVo.setInvoiceType("3");
        }

        //非电子票（申请的发票）
        if (selfOrderNotIds.size() > 0) {
            //申请以及，invoiceApplyStatus 0未审核，1审核通过，2审核不通过 ,String invoiceApplyProxyType 代开标记 0否 1是 默认0 String invoiceOrderUpdateflag (0 已开票 1未开票 ,默认0)
            // InvoiceNormalType  开票类型 0个人开票 1企业开票 默认0',
            this.insertRetrunId(member, addInvoiceVo, selfOrderNotIds, orderInfoList, "0", "0", "1", null, addInvoiceVo.getInvoiceNormalType());
        }
       /* else {
            //其他
            //申请以及，invoiceApplyStatus 0未审核，1审核通过，2审核不通过 ,String invoiceApplyProxyType 代开标记 0否 1是 默认0 String invoiceOrderUpdateflag (0 已开票 1未开票 ,默认0)
            this.insertRetrunId(member, addInvoiceVo, selfOrderIds, orderInfoList, "0", "0", "1",null);
        }*/
        //代开发票 以桩群为一组做 开票
        for (Long key : proxyhashMap.keySet()) {
            //申请以及，invoiceApplyStatus 0未审核，1审核通过，2审核不通过 ,String invoiceApplyProxyType 代开标记 0否 1是 默认0 String invoiceOrderUpdateflag (0 已开票 1未开票 ,默认0)
            // InvoiceNormalType  开票类型 0个人开票 1企业开票 默认0',
            this.insertRetrunId(member, addInvoiceVo, proxyhashMap.get(key), orderInfoList, "0", "1", "1", null, "0");
        }

        return TResponse.SUCCESS();
    }


    @Override
    @Transactional
    public InvoiceApply insertRetrunId(MemberInfo member, InvoiceApplyVo addInvoiceVo, List<Long> orderIdList, List<OrderInfo> orderInfoList, String invoiceApplyStatus, String invoiceApplyProxyType,
                                       String invoiceOrderUpdateflag, ReturnElectronice invEli, String invoiceNormalType) {
        InvoiceApply invoiceApply = dozerMapper.map(addInvoiceVo, InvoiceApply.class);
        BigDecimal amount = new BigDecimal(0);

        for (Long orderId : orderIdList) {
            OrderInfo orderInfo = orderInfoList.stream().filter(orderInfo1 -> orderId.equals(orderInfo1.getOrderId())).findFirst().orElseGet(() -> null);
            if (orderInfo != null) {
                amount = amount.add(orderInfo.getPayAmount());
                if ("1".equals(invoiceApplyProxyType)) {
                    invoiceApply.setElecStationId(orderInfo.getElecStationId());
                }
            }
        }

        invoiceApply.setTenantCode(member.getTenantCode());
        invoiceApply.setMemberId(member.getMemberId());
        invoiceApply.setAmount(amount);
        invoiceApply.setInvoiceNormalType(invoiceNormalType);
        invoiceApply.setCompanyName(invoiceApply.getInvoiceTitle());

        invoiceApply.setCreatedBy(String.valueOf(member.getMemberId()));
        invoiceApply.setStatus(invoiceApplyStatus);
        invoiceApply.setProxyType(invoiceApplyProxyType);

        invoiceApply.setLastUpdatedTime(new Date());
        invoiceApply.setCreatedTime(new Date());
        invoiceApply.setLastUpdatedBy(String.valueOf(member.getMemberId()));
        invoiceApplyMapper.insertRetrunId(invoiceApply);
        Invoice invoice = new Invoice();
        if ("0".equals(invoiceOrderUpdateflag)) {
            //电子发票直接生成数据
            //Insert invoice_order
            invoice.setTenantCode(member.getTenantCode());
            invoice.setMemberId(member.getMemberId());
            invoice.setInvoiceType("3");

            invoice.setInvoiceApplyId(invoiceApply.getInvoiceApplyId());
            invoice.setInvoiceTitle(invoiceApply.getInvoiceTitle());
            invoice.setAmount(invoiceApply.getAmount());
            invoice.setCompanyName(invoiceApply.getCompanyName());
            invoice.setCompanyCredit(invoiceApply.getCompanyCredit());
            invoice.setCompanyAddress(invoiceApply.getCompanyAddress());
            invoice.setCompanyTel(invoiceApply.getCompanyTel());
            invoice.setCompanyBank(invoiceApply.getCompanyBank());
            invoice.setCompanyBankAccount(invoiceApply.getCompanyBankAccount());
            invoice.setProvinceId(invoiceApply.getProvinceId());
            invoice.setCityId(invoiceApply.getCityId());
            invoice.setAreaId(invoiceApply.getAreaId());
            invoice.setAddress(invoiceApply.getAddress());
            invoice.setLicenseImg1(invoiceApply.getLicenseImg1());
            invoice.setLicenseImg2(invoiceApply.getLicenseImg2());
            invoice.setLicenseImg2(invoiceApply.getLicenseImg3());

            invoice.setProxyType("0");
            invoice.setRequestNo(invEli.getFPQQLSH().getValue());
            invoice.setRedType("0");
            invoice.setPdfUrl(invEli.getPDFURL().getValue());
            invoice.setInvoiceDate(invEli.getKPRQ().getValue());
            invoice.setInvoiceCode(invEli.getFPHM().getValue());
            invoice.setCreatedTime(new Date());
            invoice.setLastUpdatedTime(new Date());
            invoiceMapper.insertReturnId(invoice);
            logger.info("电子发票生成ID,{}", invoice.getInvoiceId());
            for (Long orderId : orderIdList) {
                InvoiceOrder invoiceOrder = new InvoiceOrder();
                invoiceOrder.setOrderId(orderId);
                invoiceOrder.setInvoiceId(invoice.getInvoiceId());
                invoiceOrder.setTenantCode(member.getTenantCode());
                invoiceOrder.setInvoiceApplyId(invoiceApply.getInvoiceApplyId());
                invoiceOrder.setUpdateFlag(invoiceOrderUpdateflag);
                invoiceOrder.setCreatedBy(String.valueOf(member.getMemberId()));
                invoiceOrder.setMemberId(member.getMemberId());
                invoiceOrder.setCreatedTime(new Date());
                invoiceOrder.setLastUpdatedBy(String.valueOf(member.getMemberId()));
                invoiceOrder.setLastUpdatedTime(new Date());
                invoiceOrderMapper.insertSelective(invoiceOrder);
                OrderInfo orderInfo = orderInfoList.stream().filter(orderInfo1 -> orderId.equals(orderInfo1.getOrderId())).findFirst().orElseGet(() -> null);
                logger.info("订单,{}电子发票生成ID,{}", orderInfo.getOutOrderNum(), invoiceOrder.getInvoiceId());
                orderInfo.setInvoiceId(invoiceOrder.getInvoiceId());
                orderInfoService.updateByPrimaryKeySelective(orderInfo);

            }
        } else {
            for (Long orderId : orderIdList) {
                InvoiceOrder invoiceOrder = new InvoiceOrder();
                invoiceOrder.setOrderId(orderId);
                invoiceOrder.setTenantCode(member.getTenantCode());
                invoiceOrder.setInvoiceApplyId(invoiceApply.getInvoiceApplyId());
                invoiceOrder.setUpdateFlag(invoiceOrderUpdateflag);
                invoiceOrder.setCreatedBy(String.valueOf(member.getMemberId()));
                invoiceOrder.setMemberId(member.getMemberId());
                invoiceOrder.setCreatedTime(new Date());
                invoiceOrder.setLastUpdatedBy(String.valueOf(member.getMemberId()));
                invoiceOrder.setLastUpdatedTime(new Date());
                invoiceOrderMapper.insertSelective(invoiceOrder);
            }
        }
        HashMap<String, Long> map = new HashMap<>();
        map.put("invoiceApplyId", invoiceApply.getInvoiceApplyId());

        mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map));
        RcMsgNotification rcMsgNotification=new RcMsgNotification();
        rcMsgNotification.setTenantCode(member.getTenantCode());
        rcMsgNotification.setMsgType("5");
        rcMsgNotification.setMsgId(invoiceApply.getInvoiceApplyId().toString());
        rcMsgNotificationService.saveRcMsgNotification(rcMsgNotification);

        return invoiceApply;

    }

    @Override
    public TResponse createEntInvoice(InvoiceApplyVo invoiceApplyVo, MemberInfo member) {

        //企业主会员
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectByMemberId(member.getMemberId());
        Long enterpriseId = enterpriseMember != null ? null : enterpriseMember.getEnterpriseId();

        //订单id获取（按照多个月份）
        List<String> yearMoths = Arrays.asList(invoiceApplyVo.getYearMonth().split(","));
        List<OrderInfoVo> orderVoList = new ArrayList<>();
        for (String yearMonth : yearMoths) {


            List<OrderInfoVo> orderVoList1 = orderInfoMapper.listEntOrderWithoutInvoiceByMember(member.getTenantCode(), member.getMemberId(), enterpriseId, yearMonth);
            if (orderVoList1 != null) {
                orderVoList.addAll(orderVoList1);
            }
        }

        List<Long> orderIdList = orderVoList.stream().map(OrderInfoVo::getOrderId).collect(Collectors.toList());

        if (orderIdList.size() == 0) {
            return TResponse.FAIL(invoiceApplyVo.getYearMonth() + "无订单");
        }

        //订单排除
        //审核中和审核通过的订单
        InvoiceApplyExample invoiceApplyExample = new InvoiceApplyExample();
        invoiceApplyExample.createCriteria().andMemberIdEqualTo(member.getMemberId()).andStatusNotEqualTo(WebConstant.CON2);
        List<InvoiceApply> invoiceApplies = invoiceApplyMapper.selectByExample(invoiceApplyExample);
        //审核中和审核通过的订单 和订单id
        List<Long> invoiceApplyIds = invoiceApplies.stream().map(InvoiceApply::getInvoiceApplyId).collect(Collectors.toList());
        List<InvoiceOrder> invoiceOrderList = new ArrayList<>();
        if (invoiceApplyIds.size() > 0) {
            InvoiceOrderExample example = new InvoiceOrderExample();
            example.createCriteria().andInvoiceApplyIdIn(invoiceApplyIds).andMemberIdEqualTo(member.getMemberId()).andOrderIdIn(orderIdList);
            invoiceOrderList = invoiceOrderService.selectByExample(example);
        }


        OrderInfoExample orderInfoExample = new OrderInfoExample();
        orderInfoExample.createCriteria().andOrderIdIn(orderIdList).andStatusEqualTo(WebConstant.CON2);
        List<OrderInfo> orderInfoList = orderInfoService.selectByExample(orderInfoExample);

        if (invoiceOrderList.size() > 0) {
            List<String> orderNums = new ArrayList<>();
            invoiceOrderList.forEach(invoiceOrder -> {
                List<OrderInfo> list = orderInfoList.stream().filter(order -> order.getOrderId().equals(invoiceOrder.getOrderId())).collect(Collectors.toList());
                orderNums.add(list.get(0).getOrderNum());
            });
            logger.info("invoice.checkOrderInvoice:" + orderNums.toString() + ",该订单号已经在申请中，请重新选择！");
            return TResponse.FAIL(orderNums.toString() + ",该订单号已经在申请中，请重新选择！");
        }

        if ("2".equals(invoiceApplyVo.getInvoiceType())) {
            invoiceApplyVo.setInvoiceType("3");
        }
        //非电子票（申请的发票）
        if (orderIdList.size() > 0) {
            //申请以及，invoiceApplyStatus 0未审核，1审核通过，2审核不通过 ,String invoiceApplyProxyType 代开标记 0否 1是 默认0 String invoiceOrderUpdateflag (0 已开票 1未开票 ,默认0)
            // InvoiceNormalType  开票类型 0个人开票 1企业开票 默认0',
            this.insertRetrunId(member, invoiceApplyVo, orderIdList, orderInfoList, "0", "0", "1", null, "1");
        }
        return TResponse.SUCCESS();
    }


}
